<template>
  <div class="w-[100%] h-[100%] flex">
    <div class="left w-[938px]">
      <el-button size="large" class="w-[80px]">
        <div class="w-[12px] h-[12px] bg mr-[5px]"
             @click="handleBtnClick({type:'back'})"
             style="background-image: url(https://img.alicdn.com/imgextra/i3/801089336/O1CN01esxE5R2IpwkB2inWV_!!801089336.png)"></div>
        返回
      </el-button>

      <div class="mt-[30px] text-[20px]">
        席位购买
      </div>

      <div class="mt-[30px] flex">
        <div class="text-[#666666] mr-[40px]">账户ID:viviweiomilad</div>
        <div class="text-[#666666]">已有席位：<span
          class="text-[#3721FF]">{{ companyInfo.accountCount || 0 }}</span>个
        </div>
      </div>

      <div
        class="px-[16px] py-[16px] flex items-center bg-[rgba(255,78,0,0.03)] rounded-[8px] mt-[20px]">
        <Icon icon="ep:bell-filled" color="#FF4E00"/>
        <span
          class="ml-[10px] text-[#FF4E00]">     温馨提示：当前版本可用席位使用率已达100%（当前可用：0），请及时扩容以保证团队正常使用</span>
      </div>


      <div class="flex items-center mt-[20px]" v-style="`gap:10px`">
        <div class="w-[110px] text-right">购买席位数量：</div>

        <div>
          <el-input-number v-model="num"/>
          个
        </div>
      </div>

      <div class="left relative mr-[24px] text-right mt-[20px] ">
        <div class="w-[110px] text-right">支付方式：</div>

        <div class="text-[12px] text-[#999999] ml-[24px] absolute top-[3px] left-[95px]"
             style="white-space: nowrap">
          有效防止恶意下单
        </div>

        <div class="flex mt-[20px]">
          <div class="w-[120px]">

          </div>
          <div
            v-for="(item,index) in method"
            :key="index"
            class="w-[183px] h-[54px] bg mr-[10px]"
            style="background-size: contain"
            @click="handleBtnClick({type:'switchMethod',index})"
            :style="`background-image:url(${ activeMethod == index ? 'https://img.alicdn.com/imgextra/i2/801089336/O1CN01l9BsIZ2IpwkN4GrOD_!!801089336.png' : 'https://img.alicdn.com/imgextra/i2/801089336/O1CN01IpLkRy2IpwkMZD1YZ_!!801089336.png' })`"

          >
            <div class="w-[100%] h-[100%] bg" :style="`background-image:url(${ item.url })`">

            </div>

          </div>
        </div>

      </div>


      <div class="mt-[63px] w-[659px] h-[104px] bg"
           style="background-image: url(https://img.alicdn.com/imgextra/i1/801089336/O1CN01xd7y2S2IpwkB3yoae_!!801089336.png)">

      </div>

      <div class="mt-[30px]">
        <el-button round color="#3a24ff" type="primary" @click="handleBtnClick({type:'buy'})">
          立即购买
        </el-button>
      </div>

    </div>
    <!--    -->
    <div class="right flex-center h-[100%] pl-[20px]" v-if="isShowBarCode">
      <div>
        <div style="border:  solid 1px #F5F5F5" class="px-[20px] py-[20px]">


          <div class="w-[240px] h-[240px] barCodeContainer">
            <canvas :id="ctxId" v-style="`width: 100%;height:100%;`" class=""
            >

            </canvas>
          </div>

        </div>

        <div class="mt-[40px] flex-center">应付金额：<span
          class="text-[22px] text-[#FF4E00]">￥{{ computeRestPrice() }}</span></div>

      </div>
    </div>
  </div>
</template>
<script setup lang="ts">

import {useAppStore} from "@/store/modules/app";
import {useMessage} from "@/hooks/web/useMessage";

const app = useAppStore();


import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";

const payType = getStrDictOptions(DICT_TYPE.PAY_TYPE);
const businessType = getStrDictOptions(DICT_TYPE.BUSINESS_TYPE);


import {FeeApi} from "@/api/fee";
import router from "@/router";
import Icon from "../../../../components/Icon/src/Icon.vue";
import {getCompanayInfo} from "@/api/system/tenant";

import {OneThaliApi} from "@/api/system/tenant/flow";
import {throttle} from "@/utils";
import dayjs from "dayjs";
import QRCode from "qrcode";

const ctxId = ref(`ctx${+new Date()}`)

const config = ref([
  {
    value: "66.66"
  },
  {
    value: "88.88",
    less: 200
  },
  {
    value: "99.99"
  },
  {
    value: "168.88",
    less: 200
  },
  {
    value: "666.66",
    less: 200
  }
])

const active = ref(-1);

const num = ref(1);

const isShowBarCode = ref(false);

const orderInfo = ref({})


const method = ref([
  {
    name: "微信",
    url: "https://img.alicdn.com/imgextra/i1/801089336/O1CN01SQDNVm2IpwkNl7RN8_!!801089336.png",
    code: "wechat",
    code1: "wx_native"
  },
  {
    name: "支付宝",
    url: "https://img.alicdn.com/imgextra/i4/801089336/O1CN01Rr4m0A2IpwkMbwTq6_!!801089336.png",
    code: "alipay",
    code1: "alipay_qr"
  }
])

const seatInfo = ref({})

const activeMethod = ref(0)

const companyInfo = ref({});

const submitInfo = ref({})

const handleBtnClick = e => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }
}


const fn = {
  switchMethod({index}) {
    if (activeMethod.value != index) {
      activeMethod.value = index;
      isShowBarCode.value = false;
    }
  },
  money({index, item}) {
    active.value = index;
    money.value = item.value
  },
  back() {
    router.go(-1)
  },
  //立即购买
  buy: throttle(async () => {

    let res = await FeeApi.generateOrder({
      types: payType.find(at => at.label == '席位')?.value,
      tenantPackageId: seatInfo.value.id,
      business: businessType.find(at => at.label == '席位购买')?.value,
      seat: num.value,//seatInfo.value.dataValue || 0,
      price: Math.round((computeRestPrice()) * 100),
      name: seatInfo.value.thali,
      duration: 1,
      expireDate: dayjs().add(1, 'month').format('YYYY-MM-DD HH:mm:ss')
    })

    orderInfo.value = res;


    getBarCode();

    // 生成二维码
  }, 1000)
}

const getBarCode = async () => {
  let res = await FeeApi.submitOrder({
    channelCode: method.value[activeMethod.value].code1,
    returnUrl: "https://blog.csdn.net/xiao_qiang666/article/details/148592009",
    id: orderInfo.value.payOrderId,
    displayMode: "qr_code",
    channelExtras: orderInfo.value
  })
  submitInfo.value = res;

  isShowBarCode.value = true;
  nextTick(() => {
    initCanvas()
  })
}

const initCanvas = () => {
  const canvas = document.getElementById(ctxId.value);

  let dom = document.querySelector('.barCodeContainer');

  QRCode.toCanvas(
    canvas,
    submitInfo.value.displayContent || '',//props.content,
    {
      scale: 4, // 二维码的每个点的像素大小
      width: dom.offsetWidth, // 在浏览器中显示的宽度
      margin: 1 // 二维码周围的空白边距
    }
  );
};


const initPromise = async () => {
  let res = await Promise.all([getCompanayInfo(), OneThaliApi.getSeat()])

  console.log(res, "rrrrrrrrrrrrr")

  let balance = res[0].balance || 0;
  balance = Math.round(balance)/100
  companyInfo.value = {
    ...res[0],
    balance:balance.toString()
  }

  let obj = res[1] || {}

  seatInfo.value = {
    ...obj,
    amount:Math.round(obj.amount)/100
  }


}

onMounted(() => {
  initPromise();
})

const generateInfo = () => {
  let option = {
    orderInfo: orderInfo.value,
    selectedPackage: {
      packageCount: seatInfo.value.dataValue,
      discountPrice: computeRestPrice(),//seatInfo.value.amount,
      //...props.selectedPackage,
      time: dayjs(submitInfo.value.successTime).format('YYYY-MM-DD HH:mm:ss'),
      type: 2,
      method: method.value[activeMethod.value].name
    }
  }

  return option
}


//计算剩余价格
const computeRestPrice = () => {
  const daysInCurrentMonth = dayjs().daysInMonth();
  let today = new Date().getDate();
  return ((seatInfo.value.amount) * (1-(today / daysInCurrentMonth)) * num.value).toFixed(2)
}


watch(() => app.payStatus, () => {
  if (app.payStatus) {
    sessionStorage.setItem('payInfo', JSON.stringify(generateInfo()))
    app.payStatus = false;
    router.push(`/fee/fee/paid`);
  }
}, {
  immediate: true
})


watch(() => num.value, () => {
  isShowBarCode.value = false;
}, {
  immediate: true
})

</script>
<style lang="scss" scoped>
.badget {
  background: linear-gradient(to right, #ff6212, #ffb74f);
}
</style>
